const express = require('express');
const STS = require('qcloud-cos-sts');
const { COS_CONFIG } = require('./config');

const app = express();

app.use((_, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Expose-Headers', '*');
    res.setHeader('Access-Control-Allow-Credentials', true);
    res.setHeader('Access-Control-Allow-Method', 'GET,POST,PUT,DELETE');
    next();
});

// 配置参数
var config = {
    secretId: COS_CONFIG.SecretId,
    secretKey: COS_CONFIG.SecretKey,
    durationSeconds: 1800,
    bucket: COS_CONFIG.Bucket,
    region: COS_CONFIG.Region,
    // 允许操作（上传）的对象前缀，可以根据自己网站的用户登录态判断允许上传的目录，例子： user1/* 或者 * 或者a.jpg
    // 请注意当使用 * 时，可能存在安全风险，详情请参阅：https://cloud.tencent.com/document/product/436/40265
    allowPrefix: [
        'test/*',
        'hdtx/*',
    ],
    // 密钥的权限列表
    allowActions: [
        // 所有 action 请看文档 https://cloud.tencent.com/document/product/436/31923
        // 简单上传
        "name/cos:GetBucket",
        "name/cos:GetObject",
        "name/cos:HeadObject",
        "name/cos:PutObject",
        "name/cos:OptionsObject",
        "name/cos:PostObject",
        "name/cos:DeleteObject"
    ],
};

app.get('/sts', function (req, res) {

    // TODO 这里根据自己业务需要做好放行判断
    // if (config.allowPrefix === '_ALLOW_DIR_/*') {
    //     res.send({error: '请修改 allowPrefix 配置项，指定允许上传的路径前缀'});
    //     return;
    // }

    // 获取临时密钥
    var LongBucketName = config.bucket;
    var ShortBucketName = LongBucketName.substr(0, LongBucketName.lastIndexOf('-'));
    var AppId = LongBucketName.substr(LongBucketName.lastIndexOf('-') + 1);

    var policy = {
        'version': '2.0',
        'statement': [{
            'action': config.allowActions,
            'effect': 'allow',
            'resource': config.allowPrefix.map((prefix) => 'qcs::cos:' + config.region + ':uid/' + AppId + ':prefix//' + AppId + '/' + ShortBucketName + '/' + prefix),
        }],
    };
    var startTime = Math.round(Date.now() / 1000);

    STS.getCredential({
        secretId: config.secretId,
        secretKey: config.secretKey,
        proxy: config.proxy,
        region: config.region,
        durationSeconds: config.durationSeconds,
        policy: policy,
    }, function (err, tempKeys) {
        if (tempKeys) tempKeys.startTime = startTime;
        res.send(err || tempKeys);
    });
});

app.listen(8004, () => {
    console.log('server is running: http://localhost:8004');
});
